package com.thiny.android.app.tsms.logic;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.thiny.android.app.tsms.util.AccessTokenKeeper;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.sso.SsoHandler;

public class ShareLogic {

	private static final String WEIBO_APP_KEY = "3036130652";
	private static final String WEIBO_REDIRECT_URL = "http://bianxin.com";
	private SsoHandler mSsoHandler;

	private ShareLogic() {
	}

	public static ShareLogic getInstance() {
		return new ShareLogic();
	}

	public void makeSureAccessTokenUseful(final Activity activity,
			final WeiboAuthListener listener) {
		// Oauth2AccessToken accessToken = AccessTokenKeeper
		// .readAccessToken(activity);
		// if (accessToken) {
		//
		// }
		Weibo weibo = Weibo.getInstance(WEIBO_APP_KEY, WEIBO_REDIRECT_URL);
		if (mSsoHandler == null) {
			mSsoHandler = new SsoHandler(activity, weibo);
		}
		mSsoHandler.authorize(new WeiboAuthListener() {

			@Override
			public void onWeiboException(WeiboException arg0) {
				// TODO Auto-generated method stub
				listener.onWeiboException(arg0);
			}

			@Override
			public void onError(WeiboDialogError arg0) {
				// TODO Auto-generated method stub
				listener.onError(arg0);

			}

			@Override
			public void onComplete(Bundle values) {

				String token = values.getString("access_token");
				String expires_in = values.getString("expires_in");
				Oauth2AccessToken accessToken = new Oauth2AccessToken(token,
						expires_in);
				AccessTokenKeeper.keepAccessToken(activity, accessToken);
				listener.onComplete(values);

			}

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				listener.onCancel();

			}
		});
	}

	public void weiboAuthorizeCallBack(int requestCode, int resultCode,
			Intent data) {
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	public void shareToWeibo(Context context, String text,
			RequestListener listener) {
		Oauth2AccessToken accessToken = AccessTokenKeeper
				.readAccessToken(context);
		StatusesAPI api = new StatusesAPI(accessToken);
		api.update(text, "0.0", "0.0", listener);
	}
}
